#include "esp8266.h"
#include "string.h"
#include "stdio.h"
extern UART_HandleTypeDef huart2;
extern uint8_t buffer[512];
extern uint16_t num;
void ESP8266_init(void)
{
   HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,GPIO_PIN_RESET);

  // GPIO_PinState
  HAL_Delay(20);
	HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,GPIO_PIN_SET);
  HAL_Delay(20);
	uint8_t ret=ESP8266_response("csum 0xde\r\n",2000);
	
	ESP8266_setbaud(115200);
	ret=ESP8266_response("ready\r\n",1000);
  /* USER CODE END 2 */
  printf("%s",buffer);
	num=0;
	memset(buffer,0,512);

}

uint8_t ESP8266_response(const char*msg,uint32_t timeout)
{
    uint32_t Cur_Tick=HAL_GetTick();
	  uint8_t data;
	  uint8_t i=0;
	 while(1)
	 {
	    if(HAL_GetTick()-Cur_Tick>=timeout)
			  return 0;
			
			
			if(HAL_UART_Receive(&huart2,&data,1,10)==HAL_TIMEOUT)
		      continue;
		  // printf("%c",data);
			buffer[num++]=data;
			if(data==msg[i])
			{i++;
				if(i==strlen(msg))
				{
				  return 1;
				
				}
			}
			else 
			{i=0;}
	
	 }

  // return 0;


}
void ESP8266_setbaud(uint32_t baud)
{
  huart2.Instance = USART2;
  huart2.Init.BaudRate = baud;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  HAL_UART_Init(&huart2);

}
void ESP8266_wifi_connect(const char*name,const char*password)
{
     char buffer[128]={0};
     sprintf(buffer,"AT+CWJAP=\"%s\",\"%s\"",name,password);
		 
	   HAL_UART_Transmit(&huart2,(uint8_t *)buffer,strlen(buffer),HAL_MAX_DELAY);
	   
	   HAL_UART_Transmit(&huart2,(uint8_t *)"\r\n",strlen(buffer),HAL_MAX_DELAY);
	   
	
	    if(ESP8266_response("OK",10000))
			{
			   printf("%s",buffer);
				
			
			}
			else
			{
			
			   printf("%s",buffer);
				 printf("connect fail");
			
			
			}
			memset(buffer,0,512);

}